var express = require('express');
var router = express.Router();
var models =require('../server/model/models');
var mongoose = require('mongoose');
var UserModel = mongoose.model('UserModel');

//GetAll
router.get('/GetUsersList', function(req, res, next) {
    return UserModel.find(function(err,userslist){
        if (err)
            res.send(404,err);
        console.log(userslist);
        res.json(userslist);
    });
});

// Insert
router.post('/newUser', function(req,res) {
    console.log(req);
    //console.log( req.user.name);
    var user = {};
   // if (req.body._id == 0) {
        user = new UserModel(
            {
                name : req.body.name,
                gender : req.body.gender,
                birthdate : req.body.birthday,
                address : req.body.address,
                email : req.body.email,
                contactno : req.body.contactno,
                type : req.body.type
            });
        user.save(function(err) {
            if (err) {
                res.send(500, err);
                console.log('error');
            }
            else {
                res.json(user);
                console.log('save');
            }


        });
  //  }
});

//Edit
router.post('/editUser', function(req,res) {
    var user = {};
    if (req.body._id != 0) {
        UserModal.findById(req.body._id, function (err, user) {
            if (err)
                res.send(500, err);
            user.name = req.body.name;
            user.gender = req.body.gender;
            user.birthdate = req.body.birthday;
            user.address = req.body.address;
            user.email = req.body.email;
            user.contactno = req.body.contactno;
            user.type = req.body.type;

            user.save(function (err) {
                if (err)
                    res.status(500, err);
                res.json(user);
            });

        });
    }
});

//Delete
router.delete('/delUser/:id', function(req,res){
    UserModel.findById(req.params.id,function(err,user){
        if (user)
            user.remove();
    });
    res.send("");
});

module.exports = router;
